package new_clue_lou_lou

import (
	"hft/Database/admin/user_db"
	"hft/Http/Services/new_clue_lou/clue_lou_dao"
	"hft/Http/Services/new_clue_lou/clue_lou_model"
	"hft/Http/Services/new_clue_lou/clue_lou_utils"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"hft/tools/front_user"
)

// 线索留资
type ActivityClue struct{}

// 留线索
func (*ActivityClue) Add(data *clue_lou_model.ActivityClue, token string, city int, ip string) (result *clue_lou_model.ClueRes, err error) {
	newUserPhone := tools.CorrectPhone(data.Phone)
	if claims, ok := clue_lou_utils.Jwt(token); !ok || data.Phone != "" { //验证过了
		// 验证没过
		if user, err := clue_lou_dao.FindUser(newUserPhone, city); err != nil {
			// 客户不存在就创建新的客户
			if err := clue_lou_dao.CreateUser(city, ip, *data); err != nil {
				return nil, err
			}
		} else {
			// 存在就添加线索
			var activity, err = clue_lou_dao.FindActivity(data.ActivityCode)
			if err != nil {
				return nil, err
			}
			var clue = clue_lou_dao.GenerateSingleClue(data, ip, activity.Title)
			clue.UserID = user.ID
			global.OC_DB.Create(&clue)
		}
		newPhone := utils.DesensitizePhoneNumber(data.Phone)
		var res = &clue_lou_model.ClueRes{Skip: true, Phone: data.Phone, TuoPhone: newPhone}
		// 发送验证码
		SendValid(newUserPhone)
		return res, nil
	} else {
		var activity, err = clue_lou_dao.FindActivity(data.ActivityCode)
		if err != nil {
			return nil, err
		}
		var clue = clue_lou_dao.GenerateSingleClue(data, ip, activity.Title)
		clue.UserID = uint(claims.ID)
		global.OC_DB.Create(&clue)
		// 寻找客户
		var user *user_db.User
		global.OC_DB.First(&user, claims.ID)
		newPhone := utils.DesensitizePhoneNumber(user.Phone)
		var res = &clue_lou_model.ClueRes{Skip: false, Phone: user.Phone, TuoPhone: newPhone}
		return res, nil
	}
}

// 发送验证码
func SendValid(phone string) {
	switch tools.CheckPhoneNumber(phone) {
	case 0:
		tools.AliyunSmsTool.SendValid(global.OC_CONFIG.AliyunSms.UserSend, phone, global.OC_CONFIG.AliyunSms.SmsModel)
	case 1:
		// newPhone := tools.IsAddRegion(phone, 1)
		tools.AliyunSmsTool.SendValid(global.OC_CONFIG.AliyunSms.UserSend, phone, global.OC_CONFIG.AliyunSms.SmsHKModel)
	case 2:
		// newPhone := tools.IsAddRegion(phone, 2)
		tools.AliyunSmsTool.SendValid(global.OC_CONFIG.AliyunSms.UserSend, phone, global.OC_CONFIG.AliyunSms.SmsHKModel)
	}
}

// 验证客户
func ValidUser(phone string, code string, city int) (token string, err error) {
	newPhone := tools.CorrectPhone(phone)
	if err := tools.AliyunSmsTool.VerifyValid(global.OC_CONFIG.AliyunSms.UserSend, newPhone, code); err != nil {
		return "", err
	} else {
		// 创建新的token
		var user *user_db.User
		global.OC_DB.Where("phone = ? AND city = ?", newPhone, city).First(&user)
		var j = front_user.NewJWT()
		var baseClaims = &front_user.BaseClaims{ID: int(user.ID), UUID: user.UUID}
		token, _ = j.CreateToken(j.CreateClaims(*baseClaims, global.OC_CONFIG.JWT.ExpiresTime, global.OC_CONFIG.JWT.BufferTime))
		return token, nil
	}
}

var ActivityClueService = new(ActivityClue)
